mod config;

use clap::Parser;
use config::Config;
use lazy_static::lazy_static;
use grpc_server::job_service_server::JobServiceServer;
use parrot_core::core::util::Util;
use std::io::stderr;
use std::io::stdout;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use tonic::transport::Server;
use tracing::Level;
use tracing_subscriber::fmt::writer::MakeWriterExt;
use parrot_core::core::services::job::job_service::JobService;

const CONFIG_FILE_NAME: &str = "config.toml";

lazy_static! {
    pub static ref ARGUMENT: Argument = Argument::parse();
    pub static ref CONFIG: Config = Config::parse();
}

/// Start prtd
#[derive(Parser)]
#[command(version, author, about, long_about)]
pub struct Argument {
    /// Custom the path of config file
    #[arg(short, long)]
    config_path: Option<PathBuf>,

    /// The port will listen on
    #[arg(short, long)]
    port: Option<u16>,

    /// Run this program in back
    #[arg(short, long)]
    daemonize: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    Util::log(&format!("Config: {:?}", *CONFIG));

    let app_name = Util::app_name();
    let data_dir = Util::app_dirs().data_dir();
    let err_appender = tracing_appender::rolling::daily(data_dir, format!("{app_name}.err.log"));
    let out_appender = tracing_appender::rolling::daily(data_dir, format!("{app_name}.out.log"));
    let appender = err_appender
        .with_max_level(Level::WARN)
        .and(stderr.with_max_level(Level::WARN))
        .and(out_appender.with_min_level(Level::INFO))
        .and(stdout.with_min_level(Level::INFO));

    tracing_subscriber::fmt().with_writer(appender).init();

    let ipv4 = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
    let socket = SocketAddr::new(ipv4, CONFIG.get_port());
    let job_service = JobService::new();

    Server::builder()
        .add_service(JobServiceServer::new(job_service))
        .serve(socket)
        .await?;

    println!("Hello prtd");
    Ok(())
}
